//
//  HttpManager.m
//  MakeNum
//
//  Created by 기대 여 on 08. 12. 14.
//  Copyright 2008 삼성전자. All rights reserved.
//

#import "HttpManager.h"


@implementation HttpManager

@synthesize delegate;
@synthesize receivedData;
@synthesize url;

-(id)initWithUrl:(NSString*)aURL delegate:(id<HttpManagerDelegate>)aDelegate {
	
	if( self = [super init] ) {
        
		// delegate
		self.delegate = aDelegate;
		
		// URL string을 아래와 같이 %가 필요한 곳에 붙여주는 encoding 해줘야한다.
		NSString *escapedUrl = [aURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		
		self.url = escapedUrl;
        
		// create the request 
		NSURLRequest *aRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:escapedUrl] 
                                                cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0]; 
		// create the connection with the request 
		// and start loading the data 
		NSURLConnection *aConnection=[[NSURLConnection alloc] initWithRequest:aRequest delegate:self]; 
		if (aConnection) { 
			// Create the NSMutableData that will hold 
			// the received data 
			// receivedData is declared as a method instance elsewhere 
			receivedData = [[NSMutableData data] retain]; 
		} else { 
			// inform the user that the download could not be made 
			// [todo] error
		} 	
	}
	
	return self;
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response { 
	// this method is called when the server has determined that it 
	// has enough information to create the NSURLResponse 
	// it can be called multiple times, for example in the case of a 
	// redirect, so each time we reset the data. 
	// receivedData is declared as a method instance elsewhere 
	[receivedData setLength:0]; 

    NSDictionary *responseHeaderFields;
    
    // 받은 header들을 dictionary형태로 받고
    responseHeaderFields = [(NSHTTPURLResponse *)response allHeaderFields];
    
    if(responseHeaderFields != nil)
    {
//        NSLog(@"Header: %@", [responseHeaderFields objectForKey:@"Content-Length"]);
        if([self.delegate respondsToSelector:@selector(connectionDidReceiveResponse:)]) {
            [self.delegate connectionDidReceiveResponse:response];
        }		
    }
    
    if ([responseHeaderFields objectForKey:@"Accept-Ranges"]== nil) {
        if([self.delegate respondsToSelector:@selector(connectionDidFail:)]) {
            [self.delegate connectionDidFail:self];
        }
        
        // receivedData is declared as a method instance elsewhere 
        if( receivedData != nil) {
            [receivedData release]; 
            receivedData = nil;
        }
    }    
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
	// append the new data to the receivedData 
	// receivedData is declared as a method instance elsewhere 
	[receivedData appendData:data]; 
	
	if( [self.delegate respondsToSelector:@selector(connectionDidReceiveData:)]) {
		[self.delegate connectionDidReceiveData:self];
	}	
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
	
	if([self.delegate respondsToSelector:@selector(connectionDidFail:)]) {
		[self.delegate connectionDidFail:self];
	}
	
	// release the connection, and the data object 
    
	[connection release]; 
	// receivedData is declared as a method instance elsewhere 
	if( receivedData != nil) {
		[receivedData release]; 
		receivedData = nil;
	}
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	
	if( [self.delegate respondsToSelector:@selector(connectionDidFail:)]) {
		[self.delegate connectionDidFinish:self];
	}
	
	[connection release]; 
	if( receivedData != nil) {
		[receivedData release]; 
		receivedData = nil;
	}
} 


- (void)dealloc {
	
	if( receivedData != nil) {
		[receivedData release];
	}
    [super dealloc];
	
}


@end
